package com.wave.common.util;

import cn.hutool.core.text.StrBuilder;
import com.wave.common.constant.TimeFormatConstant;
import com.wave.common.enums.ErrorCode;
import com.wave.common.exception.WaveException;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public final class Func {

    public static List<Long> strToLongList(String str) {
        return Arrays.stream(str.split(",")).map(Long::valueOf).collect(Collectors.toList());
    }

    public static String strListToStr(List<String> strings) {
        if (Func.isEmpty(strings)) {
            return "";
        }
        StrBuilder strBuilder = new StrBuilder();
        for (String string : strings) {
            strBuilder.append(string).append(",");
        }
        // 去除最后一个 ,
        return strBuilder.del(strBuilder.length() - 1, strBuilder.length()).toString();
    }


    public static boolean isEmpty(Object o) {
        return switch (o) {
            case null -> true;
            case String s -> s.isEmpty();
            case Collection<?> collection -> collection.isEmpty();
            case Map<?, ?> map -> map.isEmpty();
            default -> false;
        };
    }

    public static boolean isNotEmpty(Object o) {
        return !isEmpty(o);
    }

    public static boolean isAnyEmpty(Object... o) {
        for (Object obj : o) {
            if (isEmpty(obj)) {
                return true;
            }
        }
        return false;
    }

    public static String timeFormat(String format) {
        return LocalDateTime.now()
                .format(java.time.format.DateTimeFormatter.ofPattern(format));
    }

    public static void isAnyEmptyThrow(String errorMsg, Object... params) {
        boolean anyEmpty = Func.isAnyEmpty(params);
        if (anyEmpty) {
            throw new WaveException(ErrorCode.PARAMS_ERROR, errorMsg);
        }
    }

    /* ---------- 工具：float[] ↔ byte[] ---------- */
    public static byte[] floatArrayToBytes(float[] arr) {
        ByteBuffer bb = ByteBuffer.allocate(arr.length * 4)
                .order(ByteOrder.LITTLE_ENDIAN);
        for (float f : arr) bb.putFloat(f);
        return bb.array();
    }

    /* ---------- 工具：float[] → Byte[] ---------- */
    public static Byte[] floatArrayToWrapperBytes(float[] arr) {
        byte[] prim = floatArrayToBytes(arr);   // 先拿到 byte[]
        Byte[] wrap = new Byte[prim.length];
        for (int i = 0; i < prim.length; i++) {
            wrap[i] = prim[i];                  // 自动装箱
        }
        return wrap;
    }

    public static String now_YYYY_MM_DD_MM_HH_SS() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(TimeFormatConstant.YYYY_MM_DD_HH_MM_SS));
    }

}
